package logic

import (
	"context"
	"userrpc/internal/models"
	"userrpc/internal/util"

	"userrpc/internal/svc"
	"userrpc/pb/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userrpc.RegRequest) (*userrpc.RegResponse, error) {
	// todo: add your logic here and delete this line
	username := in.Username
	password := in.Password
	code := in.Code
	mobile := in.Mobile
	err := util.SelectUser(username)
	if err != nil {
		return &userrpc.RegResponse{
			Code: 400,
			Msg:  err.Error(),
		}, nil
	}
	co := models.Redis.Get(context.Background(), "code:"+mobile).Val()
	if code != co {
		return &userrpc.RegResponse{
			Code: 400,
			Msg:  "验证码错误",
		}, nil
	}
	err = util.Add(username, password, mobile)
	if err != nil {
		return &userrpc.RegResponse{
			Code: 400,
			Msg:  err.Error(),
		}, nil
	}
	return &userrpc.RegResponse{
		Code: 200,
		Msg:  "注册成功",
	}, nil
}
